﻿using System.Linq;
using System.Web.Mvc;
using ECatalog.Models;
using ECatalog.Models.Locations;
using ECatalog.Models.Models;
using ECatalog.Models.Shops;
using ECatalog.Models.UserModel;

namespace ECatalog.Controllers
{
    public class ModelController : Controller
    {
        private readonly ILocationRepository locationRepository;
        private readonly IModelRepository modelRepository;
        private readonly IModelBuilder modelBuilder;
        private readonly IShopRepository shopRepository;
        private readonly IUserRepository userRepository;

        public ModelController(IModelRepository modelRepository, IModelBuilder modelBuilder, ILocationRepository locationRepository, IShopRepository shopRepository, IUserRepository userRepository)
        {
            this.modelRepository = modelRepository;
            this.modelBuilder = modelBuilder;
            this.locationRepository = locationRepository;
            this.shopRepository = shopRepository;
            this.userRepository = userRepository;
        }

        [Authorize]
        public ActionResult Index()
        {
            @ViewBag.IsAdmin = userRepository.IsAdmin(User.Identity.Name);
            var models = modelRepository.GetAllModels();
            return View(models);
        }

        [Authorize]
        [HttpPost]
        public ActionResult AddModel()
        {
            @ViewBag.IsAdmin = userRepository.IsAdmin(User.Identity.Name);
            var m = modelBuilder.BuildVm(0);
            return View("Editor", m);
        }

        [Authorize]
        public ActionResult EditModel(int modelid)
        {
            @ViewBag.IsAdmin = userRepository.IsAdmin(User.Identity.Name);
            var vm = modelBuilder.BuildVm(modelid);
            return View("Editor", vm);
        }

        [Authorize]
        [HttpPost]
        public ActionResult DeleteModel(int modelid)
        {
            @ViewBag.IsAdmin = userRepository.IsAdmin(User.Identity.Name);
            modelRepository.RemoveModelById(modelid);
            return RedirectToAction("Index", "Model");
        }

        [Authorize]
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult SaveModel(ModelView modelView)
        {
            @ViewBag.IsAdmin = userRepository.IsAdmin(User.Identity.Name);
            if (ModelState.IsValid)
            {
                if (string.IsNullOrWhiteSpace(modelView.CatNumber))
                {
                    ModelState.AddModelError("CatNumber", "Не задан номер в каталоге");
                    var vm = modelBuilder.BuildVm(modelView.ModelId);
                    return View("Editor", vm);
                }
                if (modelView.ModelId == 0)
                {
                    var existCatNumber = modelRepository.ExistCatNumber(modelView.CatNumber);
                    if (existCatNumber)
                    {
                        ModelState.AddModelError("CatNumber", "Такой номер уже существует в каталоге");
                        var vm = modelBuilder.BuildVm(modelView.ModelId);
                        return View("Editor", vm);
                    }
                    var m = modelBuilder.Build(modelView);
                    var model = modelRepository.AddModel(m);
                    if (modelView.UploadedFile != null)
                    {
                        modelBuilder.SaveFile(modelView.UploadedFile, model);
                    }
                    return RedirectToAction("EditModel", "Model", new { model.ModelId });
                }
                else
                {
                    var m = modelBuilder.Build(modelView);
                    if (modelView.UploadedFile != null)
                    {
                        modelBuilder.SaveFile(modelView.UploadedFile, m);
                    }
                    modelBuilder.Save(m);
                    return RedirectToAction("EditModel", "Model", new { m.ModelId });
                }
            }
            return View("Editor", modelView);
        }

        [Authorize]
        public ActionResult EditLocation(int modelId, int shopId)
        {
            @ViewBag.IsAdmin = userRepository.IsAdmin(User.Identity.Name);
            var locationX = "0";
            var locationY = "0";
            var model = modelRepository.GetModelById(modelId);
            var shop = shopRepository.GetShop(shopId);
            var user = userRepository.GetUserByLogin(User.Identity.Name);
            if (shop != null)
            {
                var location = locationRepository.GetLocation(shopId, modelId);
                if (location != null)
                {
                    var coordinates = location.Coordinates.Split(';');
                    locationX = coordinates[0];
                    locationY = coordinates[1];
                }
                var locationViewModel = new LocationViewModel
                {
                    ShopId = shopId,
                    ModelId = modelId,
                    MapUrl = shop.MapUrl,
                    TypeImage = shop.TypeImage,
                    CatNumber = model.CatNumber,
                    LocationX = locationX,
                    LocationY = locationY,
                    OrganizationId = model.OrganizationId.HasValue ? model.OrganizationId.Value : 0,
                    User = user
                };
                return View("Location", locationViewModel);
            }
            return null;
        }

        [Authorize]
        public ActionResult SaveLocation(int modelId, int x, int y, int shopId)
        {
            @ViewBag.IsAdmin = userRepository.IsAdmin(User.Identity.Name);
            var l = new Location
            {
                ModelId = modelId,
                ShopId = shopId,
                Coordinates = x + ";" + y
            };
            var location = locationRepository.ExistLocation(modelId, shopId);
            if (location != null)
            {
                location.Coordinates = l.Coordinates;
                locationRepository.SaveLocation(location);
            }
            else
            {
                locationRepository.AddLocation(l);
            }
            return RedirectToAction("EditModel", "Model", new { modelId });
        }
    }
}
